import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class ForwarderTest_TcpSender {
    private static final int BUFFER_SIZE = 1024;

    public static void main(String[] args) {
        if (args.length != 3) {
            System.out.println("Usage: java ForwarderTest_TcpSender <file_path> <target_ip> <target_port>");
            return;
        }

        String filePath = args[0];
        String targetIP = args[1];
        int targetPort = Integer.parseInt(args[2]);


        String localIp = "0.0.0.0";      // 本地绑定的 IP（0.0.0.0 = 任意网卡）
        int localPort = 6000;            // 本地绑定端口（客户端出口端口）

        try
        {
            Socket socket = new Socket(
                    InetAddress.getByName(targetIP),
                    targetPort,
                    InetAddress.getByName(localIp),
                    localPort
            );
            FileInputStream fis = new FileInputStream(filePath);
            OutputStream out = socket.getOutputStream();

            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead;

            System.out.println("Start sending file: " + filePath);

            while ((bytesRead = fis.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush();

            // 发送结束标记
            byte[] endSignal = "END".getBytes();
            out.write(endSignal);
            out.flush();

            System.out.println("\nFile sent successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
